package actions.leetcode;

import actions.leetcode.dialog.LeetCodeConfigDialog;
import bean.ClassConfigBean;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.psi.impl.file.PsiDirectoryImpl;
import generator.ClassGenerator;
import org.jetbrains.annotations.NotNull;
import utils.CommonUtil;

import java.util.HashMap;
import java.util.Map;

public class LeetCodeGenerateAction extends AnAction {
    @Override
    public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
        LeetCodeConfigDialog.runWithCallBack(((number, url, name) -> {
            PsiDirectoryImpl nowSelect = CommonUtil.getNowSelect(anActionEvent);
            if (nowSelect == null) {
                return;
            }
            String parentPath = nowSelect.getVirtualFile().getPath();
            String parentPointPath = parentPath.replace('/', '.');
            String filePackage = parentPointPath.substring(parentPointPath.indexOf(".src.") + 5);

            Map<String, String> fileKeyMap = new HashMap<>();
            fileKeyMap.put("$package", filePackage);
            fileKeyMap.put("$link", url);
            fileKeyMap.put("$number", number);
            fileKeyMap.put("$name", number + '.' + name);

            if (ClassGenerator.generate(nowSelect, fileKeyMap,
                    new ClassConfigBean("LeetCode", "Solution" + number + ".java"))
            ) {
                nowSelect.getVirtualFile().refresh(false, true);
            } else {
                CommonUtil.showMessage("Failed!", "文件生成失败！");
            }
        }));
    }
}
